<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@include file="/pages/hy/common.jsp"%>
<%-- <%@include file="/pages/jyy/jsandcss.jsp" %> --%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>科目</title>
<script type="text/javascript">
	$(function () {
		//1.初始化Table
	    var oTable = new TableInit();
	    oTable.Init();

	    //2.初始化Button的点击事件
	    var oButtonInit = new ButtonInit();
	    oButtonInit.Init();
	    
	    $('#addModal').on('hide.bs.modal',function(){
	    	$("#addForm")[0].reset();
	    	$('#addForm').data('bootstrapValidator').resetForm(true);
	    });
	 	$('#edit').on('hide.bs.modal',function(){
	    	$("#editForm")[0].reset();
	    	$('#editForm').data('bootstrapValidator').resetForm(true);
	    });
	});
	
	var TableInit = function () {
	    var oTableInit = new Object();
	    //初始化Table
	    oTableInit.Init = function () {
	        $('#llm_clazz').bootstrapTable({
	            url: '${pageContext.request.contextPath }/Clazz/list.do',         //请求后台的URL（*）
	            method: 'get',                      //请求方式（*）
	            toolbar: '#toolbar',                //工具按钮用哪个容器
	            striped: true,                      //是否显示行间隔色
	            cache: false,                       //是否使用缓存，默认为true，所以一般情况下需要设置一下这个属性（*）
	            pagination: true,                   //是否显示分页（*）
	            sortable: false,                     //是否启用排序
	            sortOrder: "asc",                   //排序方式
	            queryParams: oTableInit.queryParams,//传递参数（*）
	            sidePagination: "server",           //分页方式：client客户端分页，server服务端分页（*）
	            pageNumber:1,                       //初始化加载第一页，默认第一页
	            pageSize: 10,                       //每页的记录行数（*）
	            pageList: [10, 20, 30],        //可供选择的每页的行数（*）
	            clickToSelect: true,                //是否启用点击选中行
	            uniqueId: "ID",                     //每一行的唯一标识，一般为主键列
	            detailView: false,                   //是否显示父子表
	            columns:  [{
	                checkbox: true
	            },{
	            	field: 'code',
	                title: '编码'
	            }, {
	                
                	field: 'cname',
	                title: '科目名称'
	            }, {
					field : 'fid',
					title : '下级分类',
					width :100,
					formatter: function (value,row,index) {
						return "<button type='button' class='btn btn-default' onclick='doAndSubordinate(" + row.id + ",\"" + row.code + "\",\"" + row.cname + "\")'>新增</button>";
				    }
				}],
	        });
		}
	    
	    //得到查询的参数
	    oTableInit.queryParams = function (params) {
	        var temp = {  
	            limit: params.limit,  
	            offset: params.offset/params.limit + 1,  
	            cname: $.trim($("#cname3").val()),
	            code: $.trim($("#code3").val()),
	        };
	        return temp;
	    };
	    return oTableInit;
	}
	
	var ButtonInit = function () {
	    var oInit = new Object();
	    var postdata = {};

	    oInit.Init = function () {
	        //初始化页面上面的按钮事件
	    };
	    return oInit;
	};
	
	//查询
	function selectByOther() {
		$('#llm_clazz').bootstrapTable('refresh');
	}
	
	//删除
	function doDel() {
		var a= $('#llm_clazz').bootstrapTable('getSelections');  
        var ids = "";
        for(var i = 0;i < a.length; i++) {
       	 if(i != a.length - 1) {
       	 	ids += a[i].id + ",";
       	 }else {
       	 	ids += a[i].id;
       	 }
        }
		 if(a.length>0) {
			//询问框
			Ewin.confirm({message : "确认要删除选择的数据吗？"}).on(
				function(e) {
					if (!e) {return;}
					$.ajax({
						type: "post",
						url: '${pageContext.request.contextPath }/Clazz/delete.do',
						data: {ids:ids},
						success: function(data){
							if(data >0) {
								toastr.success("删除成功"); 
								setTimeout(function(){  //使用  setTimeout（）方法设定定时1000毫秒
									//关闭模态框
									// 父页面刷新
									window.location.reload(); 
								},1000);
							}
						}
					});
				});
		}else {
			toastr.warning('请至少选择一条数据');
		}
	}
	
	//新增
	function doAdd() {
		$("#addForm")[0].reset();//打开模态框前进行重置
		$("#fid").val("0");
		$("#fcname").val("无父级科目");
		$("#addModal").modal(open);
	}
	
	//新增下级
	function doAndSubordinate(id, code, cname){
		$("#addForm")[0].reset();//打开模态框前进行重置
		$("#fid").val(id);
		$("#fcname").val(cname);
		$("#code").val(code + "01");
		$("#addModal").modal(open);
	}
	
	function save() {
		var bootstrapValidator = $("#addForm").data('bootstrapValidator');  
	    //开启验证
	    bootstrapValidator.validate();  
	    if (bootstrapValidator.isValid()){
	    	$.ajax({
				type : 'post',
				url : '${pageContext.request.contextPath }/Clazz/insert.do',
				data : $("#addForm").serialize(),
				async:false,
				success : function(data) {
					if (data==1) {
						toastr.success("新增成功"); 
						setTimeout(function(){  //使用  setTimeout（）方法设定定时3000毫秒
							//关闭模态框
							// 父页面刷新
							window.location.reload(); 
						},1000);
					} else if (data==2) {
						toastr.warning("该信息已存在，不能重复添加");
						$('#addModal').modal('hide');
					}else {
						toastr.warning("新增失败"); 
					}
				}
			});
	    }else {
	    	return;
	    }
	}
	
	//去修改
	function doEdit() {
		var a= $('#llm_clazz').bootstrapTable('getSelections');  
		 if(a.length==1) {
			 $("#edit").modal(open);
			 $.ajax({
					type: "post",
					url: '${pageContext.request.contextPath }/Clazz/queryById.do',
					data: {id:a[0].id},
					success: function(data){
						//var json = eval('('+ data +')');
						$('#code2').val(data.code); 
						$('#cname2').val(data.cname); 
						$('#id2').val(data.id); 
						$('#fid2').val(data.fid);
						$('#fcname2').val(data.fcname);
					}
				});
		}else {
			toastr.warning('请选择一条数据');
		}
	}
	
	//保存修改
	function saveEdit() {
		var bootstrapValidator = $("#editForm").data('bootstrapValidator');  
	    //开启验证
	    bootstrapValidator.validate();  
	    if (bootstrapValidator.isValid()){
		//获取name值并去空格
		var code=$.trim($("#code2").val());
	   	var cname=$.trim($("#cname2").val());
	   	var id=$.trim($("#id2").val());
	   		$.ajax({ 
	   		type: "post",  
		        url: "${pageContext.request.contextPath }/Clazz/update.do",  
		        data: {code:code, cname:cname, id:id},  
		        success: function (data) {  
		        	if(data == 1){
						toastr.success("修改成功"); 
						setTimeout(function(){  //使用  setTimeout（）方法设定定时3000毫秒
							//关闭模态框
							// 父页面刷新
							window.location.reload(); 
						},1000);
		        	}else if (data==2) {
		        		toastr.warning("该信息已存在");
						$('#edit').modal('hide');
					}else {
						toastr.warning("修改失败");
					}
				}
		    });
	    }else{
	    	return;
	    }
	}
	
	//关闭添加表单时清空数据
	function resets() {
		$('#addForm').data('bootstrapValidator').resetForm(true);
	}
	toastr.options.positionClass = 'toast-top-center'; //提示框的位置设置为中上 
</script>
</head>
<body>
	<div class="panel-body" style="padding-bottom:0px;">
        <div class="panel panel-default">
            <div class="panel-heading">查询条件</div>
            <div class="panel-body">
				<form id="formSearch" class="form-horizontal">
                    <div class="form-group">
						<label for="loginname" class="control-label col-sm-1">科目名称:</label>
						<div class="col-sm-3">
							<input class="form_datetime form-control" type="text" id="cname3" name="cname"  >
					    </div>
                        <label class="control-label col-sm-1" for="txt_search_departmentname">编码:</label>
                        <div class="col-sm-2">
                        	<input class="form_datetime form-control" type="text" id="code3" name="code"  >
                        </div>
                        <div class="col-sm-1" style="text-align:left;">
                            <button type="button" style="margin-left:50px" id="btn_query" class="btn btn-primary" onclick="selectByOther()">查询</button>
                        </div>
                    </div>
                </form>
            </div>
        </div>       
		
        <div id="toolbar" class="btn-group">
			<button id="btn_add" type="button" class="btn btn-default" onclick="doAdd()">
				<span class="glyphicon glyphicon-plus" aria-hidden="true"></span>新增
			</button>
			<button id="btn_edit" type="button" class="btn btn-default" onclick="doEdit()">
				<span class="glyphicon glyphicon-pencil" aria-hidden="true"></span>修改
			</button>
			<button id="btn_delete" onclick="doDel()" type="button" class="btn btn-default">
				<span class="glyphicon glyphicon-remove" aria-hidden="true"></span>删除
			</button>
		</div>
		
        <!-- 数据表格 -->
        <table id="llm_clazz"></table>
    </div>
    
    <!-- 添加 -->
	<div class="modal fade" id="addModal" tabindex="-1" role="dialog" aria-labelledby="addModalLabel" aria-hidden="true">
		data-backdrop="static" data-keyboard="false"
		<div class="modal-dialog">
			<div class="modal-content">
				<div class="modal-header">
					<button type="button" class="close" data-dismiss="modal" aria-label="Close" aria-hidden="true" onclick="resets()">&times;</button>
					<h4 class="modal-title" id="addModalLabel">新增科目信息</h4>
				</div>
				<div class="modal-body">
					<form class="form-horizontal" role="form" id="addForm" method="post">
						<input id="fid" name="fid" type="hidden">
						<div class="form-group">
							<label for="code" class="col-sm-3 control-label">编码：</label>
							<div class="col-sm-8"  style="width: 385px;">
								<input type="text" id="code" name="code" class="form-control" data-bv-notempty="true">
								<span class="xing"></span>
							</div>
						</div>
						<div class="form-group">
							<label for="cname" class="col-sm-3 control-label">科目名称：</label>
							<div class="col-sm-8"  style="width: 385px;">
								<input type="text" id="cname" name="cname" class="form-control" data-bv-notempty="true">
								<span class="xing"></span>
							</div>
						</div>
						<div class="form-group">
							<label for="cname" class="col-sm-3 control-label">父级科目：</label>
							<div class="col-sm-8"  style="width: 385px;">
								<input type="text" disabled="disabled" id="fcname" name="fcname" class="form-control" data-bv-notempty="true">
							</div>
						</div>
						<div class="modal-footer">
							<button type="button" class="btn btn-default" data-dismiss="modal"  onclick="resets()">关闭</button>
							<button type="submit" class="btn btn-primary" onclick="save()">保存</button>
						</div>
					</form>
				</div>
			</div>
		</div>
	</div>
	
	<!-- 修改 -->
	<div class="modal fade" id="edit" tabindex="-1" role="dialog" aria-labelledby="updateModalLabel" aria-hidden="true" data-backdrop="static" data-keyboard="false">
		<div class="modal-dialog">
			<div class="modal-content">
				<div class="modal-header">
					<button type="button" class="close" data-dismiss="modal"
						aria-hidden="true">&times;</button>
					<h4 class="modal-title" id="updateModalLabel">修改科目信息</h4>
				</div>
				<div class="modal-body">
					<form class="form-horizontal" role="form" id="editForm">
						<input type="hidden" id="fid2" name="fid">
						<div class="form-group">
							<label for="code2" class="col-sm-3 control-label">编码</label>
							<div class="col-sm-9">
								<input type="text" id="code2" name="code" class="form-control" style="width: 85%;" data-bv-notempty="true">
								<input type="hidden" id="id2" name="id">
							</div>
						</div>
						<div class="form-group">
							<label for="cname2" class="col-sm-3 control-label">科目名称</label>
							<div class="col-sm-9">
								<input type="text" id="cname2" name="cname" class="form-control" style="width: 85%;" data-bv-notempty="true">
								<input type="hidden" id="id2" name="id">
							</div>
						</div>
						<div class="form-group">
							<label for="cname" class="col-sm-3 control-label">父级科目：</label>
							<div class="col-sm-8"  style="width: 385px;">
								<input type="text" disabled="disabled" id="fcname2" name="fcname" class="form-control" data-bv-notempty="true">
							</div>
						</div>
						<div class="modal-footer">
							<button type="button" class="btn btn-default" data-dismiss="modal" onclick="resets()">关闭</button>
							<button class="btn btn-primary" onclick="saveEdit()">保存</button>
						</div>
					</form>
				</div>
			</div>
		</div>
	</div>
	
	<script type="text/javascript">
		$(function() {
			var layerTips = parent.layer === undefined ? layui.layer : parent.layer
			$("#addForm").bootstrapValidator({
				feedbackIcons : {
					valid : 'glyphicon glyphicon-ok',
					invalid : 'glyphicon glyphicon-remove',
					validating : 'glyphicon glyphicon-refresh'
				},
				fields : {
					cname : {
						validators : {
							notEmpty : {
								message : '科目名称不能为空'
							},
						}
					},
					code : {
						validators : {
							notEmpty : {
								message : '编码不能为空'
							},
						}
					},
				},
			});
			$("#editForm").bootstrapValidator({
				feedbackIcons : {
					valid : 'glyphicon glyphicon-ok',
					invalid : 'glyphicon glyphicon-remove',
					validating : 'glyphicon glyphicon-refresh'
				},
				fields : {
					cname2 : {
						validators : {
							notEmpty : {
								message : '科目名称不能为空'
							},
						}
					},
					code2 : {
						validators : {
							notEmpty : {
								message : '编码不能为空'
							},
						}
					},
				},
			});
		});
	</script>
</body>
</html>